var cf = require("../../../config.js");
var util = require("../../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var baseHandle = require("../../template/baseHandle.js");
const recorderManager = wx.getRecorderManager()
//获取应用实例
var app = getApp();
var voiceTimer = null;
var innerAudioContext = null
Page(Object.assign({}, baseHandle, {

  /**
   * 页面的初始数据
   */
  data: {
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    app: app,
    cardInfo:{},
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath,
    region:[],
    isOpen: false,//播放开关
    starttime: '00:00', //正在播放时长
    duration: '00:00', //总时长
    cardStyleId: 0,
    voiceTime:0,
    playing:false,
    reGoodList:[],
    videoUrl:''
  },
  
  //获取名片信息
  getCardInfo() {
    var ctx = this;
    wx.showLoading({
      title: '加载中',
    });
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/employee/getEmployeeInfo',
      data: {
        cusmallToken: cusmallToken
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && data.ret == 0) {
          if (data.model.employee.showPic){
            data.model.employee.showPic = data.model.employee.showPic.split(",");
          }else{
            data.model.employee.showPic = [];
          }
          if (null == data.model.employee.company) {
        	  data.model.employee.company="";
          }
          if (data.model.employee.personalProfile) {
            var profilestr = data.model.employee.personalProfile.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g, ' '); ctx.setData({
              test: profilestr
            })
          }
          if (data.model.employee.extend && data.model.employee.extend != null) {
            data.model.employee.extend = JSON.parse(data.model.employee.extend)
            var resData = data.model.employee.extend;
            if (resData.region) {
              ctx.setData({
                region: resData.region.split(',')
              })
            }
            if(resData.address && resData.address != null){
              ctx.setData({
                address:resData.address
              })
            }
            if (resData.locationInfo && resData.locationInfo.name){
              // ctx.setData({
              //   address: resData.locationInfo.name
              // })
            }
          }
          var duration;
          var sec = parseInt(data.model.employee.voiceTime || 0);
          if (60 <= sec){
            duration = "01:00";
          }else{
            if (10 > sec){
              sec = "0" + sec;
            }
            duration = "00:" + sec;
          }
          innerAudioContext.src = data.model.employee.voiceUrl;
          if ("" != data.model.employee.labels) {
        	  data.model.employee.labels = JSON.parse(data.model.employee.labels);
          } else {
			  data.model.employee.labels = [];
      }
      if(data.model.employee.headPic){
        app.drawImage(data.model.employee.headPic).then(res=>{
          ctx.setData({shareImage:res})
        })
      }
          ctx.setData({
            voiceTime: parseInt(data.model.employee.voiceTime || 0),
            duration: duration,
            cardInfo: data.model.employee,
            videoUrl:data.model.employee.videoUrl,
            cardStyleId: data.model.employee.cardStyleId==undefined?0:data.model.employee.cardStyleId
          })
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    })
  },
  linkPre: function () {
    var ctx = this;
    wx.navigateTo({
      url: '/pages/sales/look_card/pre_card?eId='+ctx.data.cardInfo.id,
    })
  },
  linkE: function () {
    wx.navigateTo({
      url: '/pages/sales/look_card/edit_card',
    })
  },
  //开始播放
  audioPlay: function () {
    var ctx = this;
    if (ctx.data.playing){
      ctx.setData({
        isOpen: true
      });
      innerAudioContext.play();
      ctx.setIntervalTimer();
      return;
    }
    ctx.setData({
      isOpen: true,
      playing:true,
      offset:0
    });
    innerAudioContext.play();
    ctx.setIntervalTimer();
  },
  playStartCb(){
    var ctx = this;
    ctx.setIntervalTimer();
  },
  setIntervalTimer(){
    var ctx = this;
    if (voiceTimer){
      return;
    }
    voiceTimer = setInterval(function () {
      console.log(ctx.data.offset);
      var curOffset = ++ctx.data.offset;
      var starttime;
      if (60 > curOffset) {
        if (10 > curOffset) {
          starttime = "00:0" + curOffset;
        } else {
          starttime = "00:" + curOffset;
        }
      } else {
        starttime = "01:00";
      }
      ctx.setData({
        offset: curOffset,
        starttime: starttime
      });
      if (ctx.data.voiceTime <= curOffset) {
        clearInterval(voiceTimer);
        voiceTimer = null;
        ctx.setData({
          isOpen: false,
          playing: false
        });
      }
    }, 1000)
  },
  //暂停播放
  audioPause: function () {
    var ctx = this;;
    innerAudioContext.pause();
    clearInterval(voiceTimer);
    voiceTimer = null;

    //由于在暂停 的间隙 也是有部分声音是可以播放的 处理暂停间隙 来回的时间差
    var curOffset = parseInt(innerAudioContext.currentTime);
    var starttime;
    if (60 > curOffset) {
      if (10 > curOffset) {
        starttime = "00:0" + curOffset;
      } else {
        starttime = "00:" + curOffset;
      }
    } else {
      starttime = "01:00";
    }
    ctx.setData({
      isOpen: false,
      offset: curOffset,
      starttime: starttime
    });
    //由于在暂停 的间隙 也是有部分声音是可以播放的
  
  },
  playEndCb(){
    var ctx = this;
    console.log("end")
    //如果当前 的播放时间 已经大于等于 总时长 请 定时器， 主要是为了处理误差造成的时间差
    if (ctx.data.voiceTime <= ctx.data.offset) {
      clearInterval(voiceTimer);
      voiceTimer = null;
      ctx.setData({
        isOpen: false,
        playing: false
      });
    }
    
  },
  //拖动进度条
  sliderChange(e) {
    var ctx = this;
    var offset = parseInt(e.detail.value);
    console.log(offset);
    ctx.setData({
      offset: offset
    });
    clearInterval(voiceTimer);
    voiceTimer = null;
    if(ctx.data.isOpen){

      ctx.setIntervalTimer();
    }
    // innerAudioContext.play();
    innerAudioContext.seek(offset)
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options,e) {
    var that = this;
    wx.hideShareMenu();
    wx.setNavigationBarTitle({
      title: '我的' + app.globalData.cardTitle,
    })
    app.getUserInfo(this, options, function (userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
      let companyMsg = wx.getStorageSync('companyInfo');
      let employee = wx.getStorageSync('employee');
      that.setData({
        companyMsg: companyMsg,
        eId: employee.id
      });
      that.fetchReGoodsList();
    });
    var iAC = wx.createInnerAudioContext();
    iAC.onEnded(that.playEndCb);
    iAC.onPlay(that.playStartCb);
    innerAudioContext = iAC;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
	  this.getCardInfo();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(voiceTimer);
    voiceTimer = null;
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角
   */
  onShareAppMessage: function(e) {
    console.log(e.target.dataset)
    let {path,title,eid} = e.target.dataset
    var ctx = this;
    let imageUrl = ctx.data.shareImage;
    if (e.from == "button" && eid && imageUrl) {
      path = `${path}?eId=${eid}&source=1`
      console.log(path)
      // util.addBehaviorTrail(eId, 3);
      //path 添加客户来源
      path += `&fromOpenId=${app.globalData.myOpenid}&fromNickName=${app.globalData.userInfo.nickName}&forwardType=page_card`;
      let shareObj = {
        title: title,
        path: path,
        imageUrl,
        success: function(res) {},
        fail: function(res) {}
      };
      return shareObj;
    }
  }
}))
